﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;
using Microsoft.AspNetCore.Cors;

namespace WTAppletProjectHTTPS.Controllers
{
    
    [EnableCors("*")]
    public class A1A2EmployeeFrameFeedingConfirmationQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] A1A2EmployeeFrameFeedingConfirmationQuery A1A2EFFCQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (A1A2EFFCQ.PageNumber <= 0 || A1A2EFFCQ.PageSize <= 0)
            {
              
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "A1A2EmployeeFrameFeedingConfirmationQueryController:分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (A1A2EFFCQ.A1A2EFFC_ID != 0)
                    {
                        whereClause += " AND FFCID = @ID";
                    }
                    if (A1A2EFFCQ.A1A2EFFC_FeedingDate != default(DateTime))
                    {
                        whereClause += " AND FFCFeedingDate = @FeedingDate";
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_ConfirmationTiming))
                    {
                        whereClause += " AND FFCConfirmationTiming LIKE @ConfirmationTiming";
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_Feeder))
                    {
                        whereClause += " AND FFCFeeder LIKE @Feeder";
                    }
                    if (A1A2EFFCQ.A1A2EFFC_FeedingQuantity > 0)
                    {
                        whereClause += " AND FFCFeedingQuantity = @FeedingQuantity";
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_ProductModel))
                    {
                        whereClause += " AND FFCProductModel LIKE @ProductModel";
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_LineBody))
                    {
                        whereClause += " AND FFCLineBody LIKE @LineBody";
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_PhotoUpload))
                    {
                        whereClause += " AND FFCPhotoUpload LIKE @PhotoUpload";
                    }

                    var query = $@"
                        SELECT 
                            FFCID, FFCFeedingDate, FFCConfirmationTiming, FFCFeeder, 
                            FFCFeedingQuantity, FFCProductModel, FFCLineBody, FFCPhotoUpload,FFCCreateCreator,FFCCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                FFCID, FFCFeedingDate, FFCConfirmationTiming, FFCFeeder, 
                                FFCFeedingQuantity, FFCProductModel, FFCLineBody, FFCPhotoUpload,FFCCreateCreator,FFCCreateTime,
                                ROW_NUMBER() OVER(ORDER BY FFCID) AS RowNum
                             FROM A1A2EmployeeFrameFeedingConfirmation {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (A1A2EFFCQ.PageNumber - 1) * A1A2EFFCQ.PageSize + 1;
                    int endRow = A1A2EFFCQ.PageNumber * A1A2EFFCQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (A1A2EFFCQ.A1A2EFFC_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = A1A2EFFCQ.A1A2EFFC_ID });
                    }
                    if (A1A2EFFCQ.A1A2EFFC_FeedingDate != default(DateTime))
                    {
                        parameters.Add(new SqlParameter("@FeedingDate", SqlDbType.DateTime) { Value = A1A2EFFCQ.A1A2EFFC_FeedingDate });
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_ConfirmationTiming))
                    {
                        parameters.Add(new SqlParameter("@ConfirmationTiming", SqlDbType.NVarChar, 50) { Value = $"%{A1A2EFFCQ.A1A2EFFC_ConfirmationTiming}%" });
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_Feeder))
                    {
                        parameters.Add(new SqlParameter("@Feeder", SqlDbType.NVarChar, 50) { Value = $"%{A1A2EFFCQ.A1A2EFFC_Feeder}%" });
                    }
                    if (A1A2EFFCQ.A1A2EFFC_FeedingQuantity > 0)
                    {
                        parameters.Add(new SqlParameter("@FeedingQuantity", SqlDbType.Int) { Value = A1A2EFFCQ.A1A2EFFC_FeedingQuantity });
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_ProductModel))
                    {
                        parameters.Add(new SqlParameter("@ProductModel", SqlDbType.NVarChar, 50) { Value = $"%{A1A2EFFCQ.A1A2EFFC_ProductModel}%" });
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_LineBody))
                    {
                        parameters.Add(new SqlParameter("@LineBody", SqlDbType.NVarChar, 50) { Value = $"%{A1A2EFFCQ.A1A2EFFC_LineBody}%" });
                    }
                    if (!string.IsNullOrEmpty(A1A2EFFCQ.A1A2EFFC_PhotoUpload))
                    {
                        parameters.Add(new SqlParameter("@PhotoUpload", SqlDbType.NVarChar, 500) { Value = $"%{A1A2EFFCQ.A1A2EFFC_PhotoUpload}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "A1A2EmployeeFrameFeedingConfirmationQueryController:未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var records = new List<A1A2EmployeeFrameFeedingConfirmation>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                records.Add(new A1A2EmployeeFrameFeedingConfirmation
                                {
                                    A1A2EFFC_ID = reader.GetInt32(reader.GetOrdinal("FFCID")),
                                    A1A2EFFC_FeedingDate = reader.GetDateTime(reader.GetOrdinal("FFCFeedingDate")),
                                    A1A2EFFC_ConfirmationTiming = reader.GetString(reader.GetOrdinal("FFCConfirmationTiming")),
                                    A1A2EFFC_Feeder = reader.GetString(reader.GetOrdinal("FFCFeeder")),
                                    A1A2EFFC_FeedingQuantity = reader.GetInt32(reader.GetOrdinal("FFCFeedingQuantity")),
                                    A1A2EFFC_ProductModel = reader.GetString(reader.GetOrdinal("FFCProductModel")),
                                    A1A2EFFC_LineBody = reader.GetString(reader.GetOrdinal("FFCLineBody")),
                                    A1A2EFFC_PhotoUpload = reader.GetString(reader.GetOrdinal("FFCPhotoUpload")),
                                    A1A2EFFC_CreateCreator = reader.GetString(reader.GetOrdinal("FFCCreateCreator")),
                                    A1A2EFFC_CreateTime = reader.GetDateTime(reader.GetOrdinal("FFCCreateTime"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = records;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = A1A2EFFCQ.PageNumber;
                            RO.PageSize = A1A2EFFCQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "A1A2EmployeeFrameFeedingConfirmationQueryController:Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
